package com.yunzhou.action;

import com.alibaba.fastjson.JSONObject;
import com.yunzhou.common.DataChangeService;
import com.yunzhou.common.DataChangeServiceImpl;
import com.yunzhou.u8.*;
import com.yunzhou.utils.LogTool;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.common.util.string.StringUtil;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * MC05、MC06流程
 * update 2022-08-04
 * 修改MC05物料统一取601
 * Created by dengxl
 */

public class createProcurementProcessNewActionMC06New implements Action {

    private Log log = LogFactory.getLog(createProcurementProcessNewActionMC06New.class.getName());
    private LogTool logTool = new LogTool("/log/huangwm/u8/action/createProcurementProcessNewActionMC06New",false);
    public String execute(RequestInfo requestInfo) {

        String requestID = requestInfo.getRequestid();//请求id
        String workflowid = requestInfo.getWorkflowid();//workflowid
        String requestname = requestInfo.getRequestManager().getRequestname();// 请求标题

        logTool.writeLog("createProcurementProcessNewAction开始====" + requestID + "，workflowid：" + workflowid);

        String ssgs = "";//分公司字段
        String company = "";//分公司
        String liucbh = "";//流程编号
        String shenqr = "";//申请人，workcode
        String shenqrq = "";//申请日期
        String shenqrd = "";//申请单位
        String shenqbm = "";//申请部门
        String shenqyy = "";//申请原因
        String xmmc1 = "";//项目名称
        String caigxm = "";//项目代号
        String xiangmdh = "";//项目号令
        String xmjll = "";//项目经理
        String xiangmzs = "";//项目总师
        String xiangmzsmc = "";//项目总师名称
        String qwdhq = "";//期望到货时间
        String shenhr = "";//审核人
        String cglx = "";//采购类型
        String cglx_value;//采购类型值

        //获取主表信息
        MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
        Property[] fields = mainTableInfo.getProperty();
        for (Property property : fields) {
            String name = property.getName();
            String value = property.getValue();
            if (name.equals("ssgs")) {
                ssgs = value;
            }
        }

        mainTableInfo = requestInfo.getMainTableInfo();
        fields = mainTableInfo.getProperty();

        for (Property property : fields) {
            String name = property.getName();
            String value = property.getValue();
            if (name.equals(ssgs)) {
                company = value;
            }
            if (name.equals("liucbh")) {
                liucbh = value;
            }
            if (name.equals("shenqr")) {
                shenqr = value;
            }
            if (name.equals("shenqrq")) {
                shenqrq = value;
            }
            if (name.equals("shenqrd")) {
                shenqrd = value;
            }
            if (name.equals("shenqbm")) {
                shenqbm = value;
            }
            if (name.equals("shenqyy")) {
                shenqyy = value;
            }
            if (name.equals("xmmc1")) {
                xmmc1 = value;
            }
            if (name.equals("caigxm")) {
                caigxm = value;
            }
            if (name.equals("xiangmdh")) {
                xiangmdh = value;
            }
            if (name.equals("xmjll")) {
                xmjll = value;
            }
            if (name.equals("xiangmzs")) {
                xiangmzs = value;
            }
            if (name.equals("qwdhq")) {
                qwdhq = value;
            }
            if (name.equals("shr")) {
                shenhr = value;
            }
            if (name.equals("cglx")) {
                cglx = value;
            }
        }
        logTool.writeLog("转换前公司 （ssgs、company）: " + ssgs + "," + company);
        logTool.writeLog("主表信息 - requestname:" + requestname + ",caigxm:" + caigxm + ",liucbh:" + liucbh + ",qwdhq:" + qwdhq + ",shenqr:" + shenqr
                + ",shenqrq:" + shenqrq + ",shenqyy:" + shenqyy + ",shenqr:" + shenqr + ",xiangmzs:" + xiangmzs + ",xmjll:" + xmjll + ",xmmc1:" + xmmc1);

        //数据转换
        DataChangeService dataChangeService = new DataChangeServiceImpl();
        HashMap ryMap = dataChangeService.getSpecifiedTableMap("hrmresource", "id", "workcode");//人员转换，传workcode
        if (StringUtil.isNotNullAndEmpty(xiangmzs) && xiangmzs != "null") {
            String[] as = xiangmzs.split(",");
            for (int k = 0; k < as.length; k++) {
                if (xiangmzsmc.equals("")) {
                    xiangmzsmc = ryMap.get(as[k]).toString();
                } else {
                    xiangmzsmc += "," + ryMap.get(as[k]);
                }
            }
        }
        HashMap mapGs = dataChangeService.getSpecifiedTableMap("hrmsubcompany", "id", "subcompanycode");//分部集合
        xmmc1 = dataChangeService.getSingleBrowseValue("xmmc", "uf_xmhdb", "id", xmmc1);

        logTool.writeLog("传入U8主表信息 - requestname:" + requestname + ",caigxm:" + caigxm + ",liucbh:" + liucbh + ",qwdhq:" + qwdhq + ",ryMap.get(shenqr).toString():" + (shenqr.isEmpty() ? "" : ryMap.get(shenqr).toString())
                + ",shenqrq:" + shenqrq + ",shenqyy:" + shenqyy + ",shenqr:" + shenqr + ",xiangmzs:" + xiangmzs + ",ryMap.get(xmjll).toString():" + (xmjll.isEmpty() ? "" : ryMap.get(xmjll).toString()) + ",xmmc1:" + xmmc1);

        workflowid = dataChangeService.getPrimevalID(workflowid);
        logTool.writeLog("最小版本id : " + workflowid);

        PuAppVouch puApp = new PuAppVouch();
        if (workflowid.equals("317")) {//MC06-研发物料采购申请
            try{
                shenhr = dataChangeService.getCurrentoperatorFromNodeName(requestID, "计划部(审核)");
                logTool.writeLog("shenhr分别是 : " + shenhr + "," + (shenhr.isEmpty() ? "" : ryMap.get(shenhr).toString()));

                //对应U8主表
                PuAppVouchHead appVouch = new PuAppVouchHead();
                appVouch.setRequestid(requestID);
                appVouch.setBiaoti(requestname);
                appVouch.setCaigxm(caigxm);
                appVouch.setLiucbh(liucbh);
                appVouch.setShenqr((shenqr.isEmpty() ? "" : ryMap.get(shenqr).toString()));
                appVouch.setShenqrq(shenqrq);
                appVouch.setShenqyy(shenqyy);
                appVouch.setXiangmdh(xiangmdh);
                appVouch.setXiangmzs(xiangmzsmc);
                appVouch.setXmjll((xmjll.isEmpty() ? "" : ryMap.get(xmjll).toString()));
                appVouch.setXmmcnew(xmmc1);
                appVouch.setCcode(liucbh);//流程编码
                appVouch.setShenhr((shenhr.isEmpty() ? "" : ryMap.get(shenhr).toString()));

                //获取流程的明细表数据
                List<JSONObject> list = getJsonArray(requestInfo.getDetailTableInfo().getDetailTable(0));
                logTool.writeLog("createProcurementProcessNewAction-明细信息 : " + list);
                int j = list.size();
                //赋值明细
                //实际数量
                String sjQuantity = "";
                PuAppVouchBody[] appVouchs = new PuAppVouchBody[j];


                //****************************将明细行ID和预算金额传到U8 KangMD 20250324  start****************************//
                //获取流程表名
                String tablename = requestInfo.getRequestManager().getBillTableName();
                int i=0;
                //查询明细行最新数据
                String sql2="select * from "+tablename+"_dt1 where mainid in (select id from "+tablename+" where requestid="+requestID+")";
                logTool.writeLog("查询明细行最新数据---------->"+sql2);
                RecordSet rs = new RecordSet();
                rs.execute(sql2);
                while (rs.next()) {
                    sjQuantity = Util.null2String(rs.getString("jycgsl"));//申请数量
                    //实际购买数量不等于0传erp
                    if (sjQuantity != null && !sjQuantity.isEmpty() && !"0".equals(sjQuantity) && !"0.00".equals(sjQuantity)){
                        String wlbm = Util.null2String(rs.getString("wlbm1"));//服务编码
                        String shul = Util.null2String(rs.getString("jycgsl"));//申请数量
                        String danj = Util.null2String(rs.getString("danj"));//预算单价
                        String jine = Util.null2String(rs.getString("jine"));//预算金额
                        String xq = Util.null2String(rs.getString("xq"));//需求人
                        String bz = Util.null2String(rs.getString("bz"));//备注
                        String sjzl = Util.null2String(rs.getString("sjzl"));//随机资料
                        String ywlx = Util.null2o(rs.getString("ywlx"));//业务类型
                        String shdz = Util.null2String(rs.getString("shdz"));//收货地址
                        String qwdhsj = Util.null2String(rs.getString("qwdhsj"));//期望到货时间
                        String qwdhrq2 = Util.null2String(rs.getString("qwdhrq2"));//采购回复到货时间

                        String id = Util.null2String(rs.getString("id"));//明细行ID
                        String mainid = Util.null2String(rs.getString("mainid"));//主表ID
                        String pkid=requestID+'_'+mainid+"_"+id;//明细行主键I=requesid_主表ID_明细行ID

                        appVouchs[i] = new PuAppVouchBody();
                        appVouchs[i].setOaid(pkid);//OA明细行主键ID
                        appVouchs[i].setWlbm(wlbm);
                        appVouchs[i].setShul(shul);
                        appVouchs[i].setDanj(danj);
                        appVouchs[i].setJine(jine);
                        appVouchs[i].setCgy(Util.null2String(ryMap.get(xq)));
                        appVouchs[i].setBeiz(bz);
                        appVouchs[i].setSjzl(sjzl);
                        appVouchs[i].setCBusType(ywlx);//0:普通采购,1:委外加工
                        appVouchs[i].setShdz(shdz);
                        appVouchs[i].setQwdhq(qwdhsj.replace("-" , ""));
                        appVouchs[i].setPuarrivaldate(qwdhrq2);

                        i++;
                    }
                }
                //****************************将明细行ID和预算金额传到U8 KangMD 20250324  end****************************//

                /*
                for (int i = 0; i < j; i++) {
                    sjQuantity = list.get(i).getString("shul");
                    //实际购买数量不等于0传erp
                    if (sjQuantity != null && !sjQuantity.isEmpty() && !"0".equals(sjQuantity) && !"0.00".equals(sjQuantity)){
                        appVouchs[i] = new PuAppVouchBody();
                        appVouchs[i].setWlbm(list.get(i).getString("wlbm"));
                        appVouchs[i].setShul(list.get(i).getString("shul"));
                        appVouchs[i].setDanj(list.get(i).getString("danj"));
                        appVouchs[i].setJine(list.get(i).getString("jine"));
                        appVouchs[i].setCgy((list.get(i).getString("xq").isEmpty() ? "" : ryMap.get(list.get(i).getString("xq")).toString()));
                        appVouchs[i].setBeiz(list.get(i).getString("bz"));
                        appVouchs[i].setSjzl(list.get(i).getString("sjzl"));
                        appVouchs[i].setCBusType(list.get(i).getString("ywlx").isEmpty() ? "0" : list.get(i).getString("ywlx"));//0:普通采购,1:委外加工
                        appVouchs[i].setShdz(list.get(i).getString("shdz"));
                        appVouchs[i].setQwdhq(list.get(i).getString("qwdhsj").isEmpty() ? "" : list.get(i).getString("qwdhsj").replace("-" , ""));
                        appVouchs[i].setPuarrivaldate(list.get(i).getString("qwdhrq2").isEmpty() ? "" : list.get(i).getString("qwdhrq2"));
                    }
                }
                 */

                logTool.writeLog("转换后公司 : " + mapGs.get(company).toString());
                puApp.setCCompany(mapGs.get(company).toString());//分公司
                if("0".equals(cglx) ){
                    cglx_value = "生产性物料采购";
                }
                else if ("1".equals(cglx)){
                    cglx_value = "研发类物料采购";
                }else {
                    cglx_value ="工程类物料采购";
                }
                puApp.setCptname(cglx_value);
                puApp.setAppVouch(appVouch);
                puApp.setAppVouchs(appVouchs);
            }catch (Exception e){
                e.printStackTrace();
                requestInfo.getRequestManager().setMessagecontent("MD06 AppVouch Error "+e.getMessage());
                return FAILURE_AND_CONTINUE;
            }
        } else if (workflowid.equals("316")) {//MC05-生产物料采购申请
            try{
                shenhr = dataChangeService.getCurrentoperatorFromNodeName(requestID, "计划部(审核)");
                logTool.writeLog("shenhr分别是 : " + shenhr + "," + (shenhr.isEmpty() ? "" : ryMap.get(shenhr).toString()));

                //对应U8主表
                PuAppVouchHead appVouch = new PuAppVouchHead();
                appVouch.setRequestid(requestID);
                appVouch.setBiaoti(requestname);
                appVouch.setLiucbh(liucbh);
                appVouch.setShenqr((shenqr.isEmpty() ? "" : ryMap.get(shenqr).toString()));
                appVouch.setShenqrq(shenqrq);
                appVouch.setShenqyy(shenqyy);
                appVouch.setCcode(liucbh);//流程编码
                appVouch.setShenhr((shenhr.isEmpty() ? "" : ryMap.get(shenhr).toString()));

                logTool.writeLog("createProcurementProcessNewAction-主表信息，Requestid："+requestID+",Biaoti："+requestname+",Liucbh："+liucbh+",Shenqr："+(shenqr.isEmpty() ? "" :ryMap.get(shenqr).toString())
                        +",Shenqrq："+shenqrq+",Shenqyy："+shenqyy+",Ccode："+liucbh+",Shenhr："+(shenhr.isEmpty() ? "" : ryMap.get(shenhr).toString()));

                //获取流程的明细表数据
                List<JSONObject> list = getJsonArray(requestInfo.getDetailTableInfo().getDetailTable(0));
                logTool.writeLog("createProcurementProcessNewAction-list明细信息 : " + list);
                int j = list.size();
                logTool.writeLog("j : " + j);
                logTool.writeLog("company == '7' : " + (company == "7"));//false
                logTool.writeLog("company.equals('7'): " + company.equals("7"));//true
                //赋值明细
                PuAppVouchBody[] appVouchs = new PuAppVouchBody[j];



                //****************************将明细行ID和预算金额传到U8 KangMD 20250324  start****************************//
                //获取流程表名
                String tablename = requestInfo.getRequestManager().getBillTableName();
                int i=0;
                //查询明细行最新数据
                String sql2="select * from "+tablename+"_dt1 where mainid in (select id from "+tablename+" where requestid="+requestID+")";
                logTool.writeLog("查询明细行最新数据---------->"+sql2);
                RecordSet rs = new RecordSet();
                rs.execute(sql2);
                while (rs.next()) {
                    String wlbm1 = Util.null2String(rs.getString("wlbm1"));//服务编码
                    String shul = Util.null2String(rs.getString("jycgsl"));//申请数量
                    String danj = Util.null2o(rs.getString("danj"));//单价
                    String jine = Util.null2o(rs.getString("jine"));//金额
                    String xqr = Util.null2String(rs.getString("xqr"));//需求人
                    String bz = Util.null2String(rs.getString("bz"));//备注
                    String ywlx = Util.null2o(rs.getString("ywlx"));//业务类型
                    String shdz = Util.null2String(rs.getString("shdz"));//收货地址
                    String qwdhsj = Util.null2String(rs.getString("qwdhsj"));//期望到货时间
                    String qwdhrq2 = Util.null2String(rs.getString("qwdhrq2"));//采购回复到货时间

                    String id = Util.null2String(rs.getString("id"));//明细行ID
                    String mainid = Util.null2String(rs.getString("mainid"));//主表ID
                    String pkid=requestID+'_'+mainid+"_"+id;//明细行主键I=requesid_主表ID_明细行ID

                    appVouchs[i] = new PuAppVouchBody();
                    appVouchs[i].setOaid(pkid);//OA明细行主键ID
                    appVouchs[i].setWlbm(wlbm1);//统一取601
                    appVouchs[i].setShul(shul);
                    appVouchs[i].setDanj(danj);
                    appVouchs[i].setJine(jine);
                    appVouchs[i].setCgy(Util.null2String(ryMap.get(xqr)));
                    appVouchs[i].setBeiz(bz);
                    appVouchs[i].setCBusType(ywlx);//业务类型 0:普通采购,1:委外加工
                    appVouchs[i].setShdz(shdz);
                    appVouchs[i].setQwdhq(qwdhsj);
                    appVouchs[i].setPuarrivaldate(qwdhrq2);

                    i++;
                }
                //****************************将明细行ID和预算金额传到U8 KangMD 20250324  end****************************//

                /*
                for (int i = 0; i < j; i++) {
                    logTool.writeLog("i进来了 : " + i + "，company : " + company + "，yzwlbm : " + list.get(i).getString("yzwlbm"));
                    appVouchs[i] = new PuAppVouchBody();
                    appVouchs[i].setWlbm(list.get(i).getString("wlbm1"));//统一取601
                    appVouchs[i].setShul(list.get(i).getString("shul"));
                    appVouchs[i].setDanj("0");
                    appVouchs[i].setJine("0");
                    appVouchs[i].setCgy(list.get(i).getString("xqr").isEmpty() ? "" : ryMap.get(list.get(i).getString("xqr")).toString());
                    appVouchs[i].setBeiz(list.get(i).getString("bz"));
                    appVouchs[i].setCBusType(list.get(i).getString("ywlx").isEmpty() ? "0" : list.get(i).getString("ywlx"));//0:普通采购,1:委外加工
                    appVouchs[i].setShdz(list.get(i).getString("shdz"));
                    //appVouchs[i].setQwdhq(list.get(i).getString("qwdhsj").isEmpty() ? "" : list.get(i).getString("qwdhsj").replace("-" , ""));
                    appVouchs[i].setQwdhq(list.get(i).getString("qwdhsj").isEmpty() ? "" : list.get(i).getString("qwdhsj"));
                    appVouchs[i].setPuarrivaldate(list.get(i).getString("qwdhrq2").isEmpty() ? "" : list.get(i).getString("qwdhrq2"));
                }
                 */
                logTool.writeLog("转换后公司 : " + mapGs.get(company).toString());

                puApp.setCCompany(mapGs.get(company).toString());//分公司
                puApp.setCptname("生产性物料采购");
                puApp.setAppVouch(appVouch);
                puApp.setAppVouchs(appVouchs);
            }catch (Exception e){
                e.printStackTrace();
                requestInfo.getRequestManager().setMessagecontent("MD05 AppVouch Error "+e.getMessage());
                return FAILURE_AND_CONTINUE;
            }

        }

        String result = "";
        try {
            logTool.writeLog("调用U8接口传入参数----->"+JSONObject.toJSONString(puApp));
            ServiceForOA workflowServiceXmlLocator = new ServiceForOALocator();//U8接口
            result = workflowServiceXmlLocator.getserviceForOASoap12().addPOVouch(puApp);
            logTool.writeLog("MC06/MC05接口返回信息===="+result);
        } catch (Exception ex) {
            logTool.writeLog("输出有值，返回了错误====" + result);
            ex.printStackTrace();
            requestInfo.getRequestManager().setMessagecontent(result);
            return FAILURE_AND_CONTINUE;
        }

        logTool.writeLog("result====" + result);
        logTool.writeLog("createProcurementProcessNewAction结束====" + requestID);

        if (result.isEmpty()) {
            return SUCCESS;
        } else {
            requestInfo.getRequestManager().setMessagecontent(result);
            return FAILURE_AND_CONTINUE;
        }

    }

    /**
     * 获取明细表数据
     *
     * @param detailTable
     * @return
     */
    private List getJsonArray(DetailTable detailTable) {
        List<JSONObject> list = new ArrayList<JSONObject>();
        for (Row row : detailTable.getRow()) {
            JSONObject jsonObject = new JSONObject();
            for (Cell cell : row.getCell()) {
                if ("gsgs".equals(cell.getName())) {//归属公司
                    jsonObject.put("ssfygs", cell.getValue());
                } else if ("wlbm1".equals(cell.getName())) {//存货编码
                    jsonObject.put("wlbm", cell.getValue());
                } else if ("yzwlbm".equals(cell.getName())) {//云智物料编码
                    jsonObject.put("yzwlbm", cell.getValue());
                } else if ("wupmc".equals(cell.getName())) {//物品名称
                    jsonObject.put("wupmc", cell.getValue());
                } else if ("guigxh".equals(cell.getName())) {//规格型号
                    jsonObject.put("guigxh", cell.getValue());
                } else if ("jycgsl".equals(cell.getName())) {//建议采购数量
                    jsonObject.put("shul", cell.getValue());
                } else if ("danw".equals(cell.getName())) {//单位
                    jsonObject.put("danw", cell.getValue());
                } else if ("danj".equals(cell.getName())) {//单价
                    jsonObject.put("danj", cell.getValue());
                } else if ("jine".equals(cell.getName())) {//金额
                    jsonObject.put("jine", cell.getValue());
                } else if ("cgy".equals(cell.getName())) {//采购员
                    jsonObject.put("cgy", cell.getValue());
                } else if ("bz".equals(cell.getName())) {//备注
                    jsonObject.put("bz", cell.getValue());
                } else if ("ywlx".equals(cell.getName())) {//业务类型
                    jsonObject.put("ywlx", cell.getValue());
                } else if ("shdz".equals(cell.getName())) {//收货地址
                    jsonObject.put("shdz", cell.getValue());
                } else if ("xqr".equals(cell.getName())) {//MC05 需求人
                    jsonObject.put("xqr", cell.getValue());
                } else if ("xq".equals(cell.getName())) {//MC06 需求人
                    jsonObject.put("xq", cell.getValue());
                }  else if ("qwdhsj".equals(cell.getName())) {//期望到货时间
                    jsonObject.put("qwdhsj", cell.getValue());
                }else if ("qwdhrq2".equals(cell.getName())) {//期望到货时间
                    jsonObject.put("qwdhrq2", cell.getValue());
                }else if ("sjzl".equals(cell.getName())) {//随机资料
                    jsonObject.put("sjzl", cell.getValue());
                }
            }
            list.add(jsonObject);
        }
        return list;
    }

}
